package Reproductor;


import java.awt.Color;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Pablo
 */
public class Reproductor extends javax.swing.JFrame {

    private String filename= "" ;
    MP3AD track = new MP3AD(filename);
    private DefaultListModel df = new DefaultListModel();
    //private String[] tracks = new String[100];
    private String[] titles = new String[100];
    private ArrayList<String> tracks = new ArrayList(30);
    private long[] pesos = new long[100];
    private int cont=0, index;
    private FileChooser selector;
    private long duracion;
    int sw=0, sw2=0; 
    Cronometro reloj;
    int nroActual=0, nroAnterior=0;
    Thread hilo;
    private final int mil = 1000;
    
    
    public Reproductor() {
        //this.removeNotify();
        //this.setUndecorated(true);
        initComponents();
        this.setSize(536,388);
        reloj = new Cronometro();
        reloj.setVisible(true);                    
        reloj.setBounds(350, 80, 130, 50);
        add(reloj);  
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        open = new javax.swing.JButton();
        previous = new javax.swing.JButton();
        play = new javax.swing.JButton();
        next = new javax.swing.JButton();
        stop = new javax.swing.JButton();
        pantalla = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        lista = new javax.swing.JList();
        timeDesp = new javax.swing.JSlider();
        timeDesp.setValue(0);
        timeDesp.setPaintTicks(false);
        timeDesp.setPaintTrack(true);
        ;
        remove = new javax.swing.JButton();
        imagen = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(null);

        open.setText("ABRIR");
        open.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openActionPerformed(evt);
            }
        });
        getContentPane().add(open);
        open.setBounds(40, 40, 80, 30);

        previous.setText("PREVIOUS");
        previous.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                previousActionPerformed(evt);
            }
        });
        getContentPane().add(previous);
        previous.setBounds(130, 40, 90, 30);

        play.setText("PLAY");
        play.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                playActionPerformed(evt);
            }
        });
        getContentPane().add(play);
        play.setBounds(230, 40, 80, 30);

        next.setText("NEXT");
        next.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nextActionPerformed(evt);
            }
        });
        getContentPane().add(next);
        next.setBounds(320, 40, 70, 30);

        stop.setText("STOP");
        stop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stopActionPerformed(evt);
            }
        });
        getContentPane().add(stop);
        stop.setBounds(400, 40, 70, 30);

        pantalla.setBackground(Color.WHITE);
        pantalla.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        pantalla.setForeground(new java.awt.Color(255, 255, 255));
        pantalla.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        pantalla.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        pantalla.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        getContentPane().add(pantalla);
        pantalla.setBounds(40, 80, 290, 60);

        DefaultListModel model = new DefaultListModel();
        lista.setModel(model);
        lista.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listaMouseClicked(evt);
            }
        });
        lista.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                listaValueChanged(evt);
            }
        });
        lista.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(lista);

        getContentPane().add(jScrollPane2);
        jScrollPane2.setBounds(40, 150, 300, 140);

        timeDesp.setBackground(new java.awt.Color(21, 21, 42));
        timeDesp.setForeground(new java.awt.Color(153, 255, 51));
        timeDesp.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                timeDespMouseClicked(evt);
            }
        });
        timeDesp.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                timeDespStateChanged(evt);
            }
        });
        timeDesp.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                timeDespMouseDragged(evt);
            }
        });
        getContentPane().add(timeDesp);
        timeDesp.setBounds(10, 320, 420, 30);

        remove.setText("REMOVE");
        remove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeActionPerformed(evt);
            }
        });
        getContentPane().add(remove);
        remove.setBounds(390, 160, 80, 30);

        imagen.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        imagen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/The KMPlayer .jpg"))); // NOI18N
        getContentPane().add(imagen);
        imagen.setBounds(0, 0, 520, 354);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void openActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openActionPerformed
        selector = new FileChooser();
        filename = selector.getNameFile().toString();
        //tracks[cont] = filename;
        tracks.add(filename);
        titles[cont] = selector.getNameFile().getName();
        pesos[cont] = selector.getTamañoFile()/1000;
        index = cont;
        cont++;        
        lista.setListData(tracks.toArray());
        if(cont==1){
            track = new MP3AD(filename);
        }
    }//GEN-LAST:event_openActionPerformed

    private void previousActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_previousActionPerformed
        if(index > 0){            
            index = lista.getSelectedIndex();
            index = index - 1;
            lista.setSelectedIndex(index);            
            this.stopActionPerformed(evt);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Reproductor.class.getName()).log(Level.SEVERE, null, ex);
            }
            filename = tracks.get(index);
            track = new MP3AD(filename);
            this.playActionPerformed(evt);
            sw=1;
        }
    }//GEN-LAST:event_previousActionPerformed

    private void playActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_playActionPerformed
        if(sw==0) {
            if(filename.length()==0){
                pantalla.setText("ABRA UN ARCHIVO PARA REPRODUCIR");
            }
            else{                
                sw=1; 
                track.play();
                duracion = (8*pesos[index])/(track.getBitrate()/1000);                
                reloj.setTimeTotal(duracion);                
                reloj.startCronometro();
                if(timeDesp.getMaximum()!=duracion){
                    timeDesp.setMaximum((int)duracion);
                }
                if(sw2==1){
                    timeDesp.setValue(0);
                    nroActual=0;
                    nroAnterior=0;    
                }
                this.avanzarDesp();
                pantalla.setText("REPRODUCIENDO  "+titles[index]);
                play.setText("PAUSE");              
            }
        }
        else {
            reloj.pauseaCronometro();
            this.detenerDesp();
            track.pause();
            play.setText("PLAY");
            pantalla.setText("PAUSADO  "+titles[index]);
        }
    }//GEN-LAST:event_playActionPerformed

    private void nextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextActionPerformed
        if(index < cont-1){
            index = lista.getSelectedIndex();
            index = index + 1;
            lista.setSelectedIndex(index);            
            this.stopActionPerformed(evt);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Reproductor.class.getName()).log(Level.SEVERE, null, ex);
            }
            filename = tracks.get(index);
            track = new MP3AD(filename);            
            this.playActionPerformed(evt);
            /*filename = tracks[index];
            track.close();
            track = new MP3AD(filename);
            track.play();
            duracion = (8*pesos[index])/(track.getBitrate()/1000);                
            reloj.setTimeTotal(duracion);  
            pantalla.setText("REPRODUCIENDO  "+titles[index]);*/
            sw=1;
        }
    }//GEN-LAST:event_nextActionPerformed

    private void stopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopActionPerformed
        reloj.stopCronometro();
        track.close();
        this.detenerDesp();
        nroActual=0;
        nroAnterior=0;
        timeDesp.setValue(0);        
        play.setText("PLAY");              
        pantalla.setText("");
    }//GEN-LAST:event_stopActionPerformed

    private void listaValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listaValueChanged
        /*if(lista.getSelectedValue()!=null){   
            //this.detenerDesp();                        
            track.close();            
            filename = lista.getSelectedValue().toString();
            index = lista.getSelectedIndex();
            reloj.stopCronometro();          
            track = new MP3AD(filename);
            track.play();
            duracion = (8*pesos[index])/(track.getBitrate()/1000);                
            reloj.setTimeTotal(duracion);                
            reloj.startCronometro();
            if(timeDesp.getMaximum()!=duracion){
                timeDesp.setMaximum((int)duracion);
                System.out.println(timeDesp.getMaximum());
            }
            timeDesp.setValue(0);
            nroActual=0;
            nroAnterior=0;
            this.avanzarDesp();
            pantalla.setText("REPRODUCIENDO  "+titles[index]);
            play.setText("PAUSE");        
            sw=1;         
        } */       
    }//GEN-LAST:event_listaValueChanged

    private void timeDespStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_timeDespStateChanged
        
    }//GEN-LAST:event_timeDespStateChanged

    private void removeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeActionPerformed
        if(lista.getSelectedValue()!=null) {
            track.close();
            reloj.stopCronometro();
            index = lista.getSelectedIndex();
            tracks.remove(index);  
            lista.setListData(tracks.toArray());    
        }
    }//GEN-LAST:event_removeActionPerformed

    private void timeDespMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_timeDespMouseDragged
        nroActual=timeDesp.getValue();     
        //track.pause();
        //this.detenerDesp();        
        //nroActual=nroActual*1000;
        //reloj.pauseaCronometro();
        if(nroActual>=nroAnterior){
            track.setTiempoBarra(1000*(nroActual/*-nroAnterior*/));              
        }
        else{
            track.setTiempoBarra2(1000*(/*nroAnterior-*/nroActual));           
        }
        track.play();
        nroAnterior = nroActual; 
        sw=1;
        //this.avanzarDesp();        
    }//GEN-LAST:event_timeDespMouseDragged

    private void timeDespMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_timeDespMouseClicked
        nroActual=timeDesp.getValue();
        //track.pause();
        //this.detenerDesp();
        //nroActual=nroActual*1000;
        //reloj.pauseaCronometro();
        if(nroActual>=nroAnterior){
            track.setTiempoBarra(1000*(nroActual/*-nroAnterior*/));              
        }
        else{
            track.setTiempoBarra2(1000*(/*nroAnterior-*/nroActual));           
        }
        track.play();
        nroAnterior = nroActual;          
        sw=1;
        //this.avanzarDesp();        
    }//GEN-LAST:event_timeDespMouseClicked

    private void listaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listaMouseClicked
        if(lista.getSelectedValue()!=null){   
            /*//this.detenerDesp();                        
            track.close();            
            filename = lista.getSelectedValue().toString();
            index = lista.getSelectedIndex();
            reloj.stopCronometro();          
            track = new MP3AD(filename);
            track.play();
            duracion = (8*pesos[index])/(track.getBitrate()/1000);                
            reloj.setTimeTotal(duracion);                
            reloj.startCronometro();
            if(timeDesp.getMaximum()!=duracion){
                timeDesp.setMaximum((int)duracion);
                System.out.println(timeDesp.getMaximum());
            }
            timeDesp.setValue(0);
            nroActual=0;
            nroAnterior=0;
            this.avanzarDesp();
            pantalla.setText("REPRODUCIENDO  "+titles[index]);
            play.setText("PAUSE");        
            sw=1;          
            */
            this.stopActionPerformed(null);
            filename = lista.getSelectedValue().toString();
            index = lista.getSelectedIndex();
            track = new MP3AD(filename);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Reproductor.class.getName()).log(Level.SEVERE, null, ex);
            }
            this.playActionPerformed(null);
            sw2=1;
        }    
    }//GEN-LAST:event_listaMouseClicked

    
    /*@Override
    public void run(){
        while(sw==1){
            try {
                Thread.sleep(mil);                
            } catch (InterruptedException ex) {
                Logger.getLogger(Reproductor.class.getName()).log(Level.SEVERE, null, ex);
            }
            nroActual+=1;
            timeDesp.setValue(nroActual);
            if(nroActual >= duracion){                
                avanzarCancion();
                nroActual=0;
                nroAnterior = 0;
            }
        }
    }*/
    
    public void avanzarCancion(){        
        index = lista.getSelectedIndex();
        index=index+1;
        lista.setSelectedIndex(index);
    }
    
    public void avanzarDesp() {
        //hilo = new Thread(this);
        //hilo.start();
        new Thread() {
            @Override
            public void run(){
                while(sw==1){
                    try {
                        Thread.sleep(mil);                
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Reproductor.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    nroActual+=1;
                    timeDesp.setValue(nroActual);
                    if(nroActual >= duracion){                
                        avanzarCancion();
                        nroActual=0;
                        nroAnterior = 0;
                    }
                }    
            }
        }.start();
    }
    
    public void detenerDesp() {
        sw=0;
    }
        /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Reproductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Reproductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Reproductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Reproductor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try{
                    JFrame.setDefaultLookAndFeelDecorated(true);
                    JDialog.setDefaultLookAndFeelDecorated(true);
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                new Reproductor().setVisible(true);
            } 
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel imagen;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JList lista;
    private javax.swing.JButton next;
    private javax.swing.JButton open;
    private javax.swing.JLabel pantalla;
    private javax.swing.JButton play;
    private javax.swing.JButton previous;
    private javax.swing.JButton remove;
    private javax.swing.JButton stop;
    private javax.swing.JSlider timeDesp;
    // End of variables declaration//GEN-END:variables

    /*@Override
    public void run() {
        throw new UnsupportedOperationException("Not supported yet.");
    }*/
}
